package com.fin.zw.intelligentbot.service;

import com.alibaba.fastjson.JSONObject;
import com.fin.zw.intelligentbot.entity.DialTask;
import com.fin.zw.intelligentbot.entity.QTaskCustomer;
import com.fin.zw.intelligentbot.entity.RobotInfo;
import com.fin.zw.intelligentbot.entity.TaskCustomer;
import com.fin.zw.intelligentbot.enums.Whether;
import com.fin.zw.intelligentbot.model.base.*;
import com.fin.zw.intelligentbot.model.interactive.TaskApi;
import com.fin.zw.intelligentbot.model.interactive.TaskMessage;
import com.fin.zw.intelligentbot.repository.DialTaskRepository;
import com.fin.zw.intelligentbot.repository.TaskCustomerRepository;
import com.google.common.collect.Lists;
import com.querydsl.core.BooleanBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("socketService")
public class SocketService {

    private static final Logger log = LoggerFactory.getLogger(SocketService.class);

//    @Value("${task.webSocketUrl}")
//    private String socketUrl;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private DialTaskRepository dialTaskRepository;

    @Autowired
    private TaskCustomerRepository taskCustomerRepository;


    /**
     * 任务的取消
     *
     * @param taskId
     */
    public void cancelTask(String taskId) {
        Optional<DialTask> optional = dialTaskRepository.findById(taskId);
        if (!optional.isPresent()) {
            log.error("任务信息不存在");
            throw new RuntimeException("任务信息不存在");
        }
        DialTask dialTask = optional.get();
        TaskApi taskApi = new TaskApi();
        taskApi.setId(taskId);
        taskApi.setName(dialTask.getName());//任务名称

        CompanyInfo companyInfo = new CompanyInfo();
        BeanUtils.copyProperties(dialTask.getCompany(), companyInfo);
        taskApi.setCompanyInfo(companyInfo);
        TaskMessage taskMessage = new TaskMessage();
        taskMessage.setCmd("cancel");
        taskMessage.setTask(taskApi);
        String json = JSONObject.toJSONString(taskMessage);
//        SocketClient.socketSend(socketUrl, json);
        rabbitTemplate.convertAndSend("task", json);
    }


    /**
     * 任务的信息推送
     *
     * @param taskId
     */
    public void sendTaskInfo(String taskId) {
        log.info("任务信息开始推送");
        PushTask pushTask = new PushTask();
        BooleanBuilder builder = new BooleanBuilder();
        QTaskCustomer qTaskCustomer = QTaskCustomer.taskCustomer;
        builder.and(qTaskCustomer.dialTask.id.eq(taskId));
        builder.and(qTaskCustomer.blacklist.eq(Whether.NO));
        Iterator<TaskCustomer> iterator = taskCustomerRepository.findAll(builder).iterator();
        List<TaskCustomer> list = Lists.newArrayList(iterator);
        if (list != null && !list.isEmpty()) {
            DialTask dialTask = list.get(0).getDialTask();
            BeanUtils.copyProperties(dialTask, pushTask);
            pushTask.setStatus(dialTask.getStatus().toString());
            Scene scene = new Scene();
            BeanUtils.copyProperties(dialTask.getScene(), scene);
            pushTask.setScene(scene);
            List<PushRobot> pushRobots = new ArrayList<>();
            for (RobotInfo robotInfo : dialTask.getRobots()) {
                PushRobot pushRobot = new PushRobot();
                BeanUtils.copyProperties(robotInfo, pushRobot);
                AiConfigura nlp = new AiConfigura();
                BeanUtils.copyProperties(robotInfo.getNlp(), nlp);
                AiAccountBase nlpAccount = new AiAccountBase();
                BeanUtils.copyProperties(robotInfo.getNlp().getAccounts(), nlpAccount);
                nlp.setAccount(nlpAccount);
                pushRobot.setNlp(nlp);
                AiConfigura asr = new AiConfigura();
                BeanUtils.copyProperties(robotInfo.getAsr(), asr);
                AiAccountBase asrAccount = new AiAccountBase();
                BeanUtils.copyProperties(robotInfo.getAsr().getAccounts(), asrAccount);
                asr.setAccount(asrAccount);
                pushRobot.setAsr(asr);
                AiConfigura tts = new AiConfigura();
                BeanUtils.copyProperties(robotInfo.getTts(), tts);
                AiAccountBase ttsAccount = new AiAccountBase();
                BeanUtils.copyProperties(robotInfo.getTts().getAccounts(), ttsAccount);
                tts.setAccount(ttsAccount);
                pushRobot.setTts(tts);
                Category category = new Category();
                BeanUtils.copyProperties(robotInfo.getGateway(), category);
                pushRobot.setGateway(category);
                pushRobots.add(pushRobot);
            }
            pushTask.setRobots(pushRobots);
        }
        List<Customer> customers = new ArrayList<>();
        for (TaskCustomer taskCustomer : list) {
            Customer customer = new Customer();
            BeanUtils.copyProperties(taskCustomer, customer, "dialogRecord,dialogContent");
            if (Objects.nonNull(taskCustomer.getAttitude()))
                customer.setAttitude(taskCustomer.getAttitude().getCode());
            customer.setStatus(taskCustomer.getStatus().toString());
            customer.setSex(taskCustomer.getSex().toString());
            customers.add(customer);
        }
        pushTask.setCustomers(customers);
        log.info("推送的任务信息是：" + pushTask);
        Map<String, Object> map = new HashMap<>();
        map.put("cmd", "start");
        map.put("task", pushTask);
        Object taskMap = JSONObject.toJSON(map);
        System.out.println(taskMap.toString());
//        SocketClient.socketSend(socketUrl, taskMap.toString());
        rabbitTemplate.convertAndSend("task", taskMap.toString());
        log.info("任务信息推送结束");
    }

    /**
     * 推送任务只退送任务信息
     *
     * @param taskId
     */
    public void sendTaskInfoById(String taskId) {
        PushTask pushTask = new PushTask();
        Optional<DialTask> optional = dialTaskRepository.findById(taskId);
        if (optional.isPresent()) {
            DialTask dialTask = optional.get();
            BeanUtils.copyProperties(dialTask, pushTask);
            pushTask.setStatus(dialTask.getStatus().toString());
            Scene scene = new Scene();
            BeanUtils.copyProperties(dialTask.getScene(), scene);
            pushTask.setScene(scene);
            List<PushRobot> pushRobots = new ArrayList<>();
            for (RobotInfo robotInfo : dialTask.getRobots()) {
                PushRobot pushRobot = new PushRobot();
                BeanUtils.copyProperties(robotInfo, pushRobot);
                AiConfigura nlp = new AiConfigura();
                BeanUtils.copyProperties(robotInfo.getNlp(), nlp);
                AiAccountBase nlpAccount = new AiAccountBase();
                BeanUtils.copyProperties(robotInfo.getNlp().getAccounts(), nlpAccount);
                nlp.setAccount(nlpAccount);
                pushRobot.setNlp(nlp);
                AiConfigura asr = new AiConfigura();
                BeanUtils.copyProperties(robotInfo.getAsr(), asr);
                AiAccountBase asrAccount = new AiAccountBase();
                BeanUtils.copyProperties(robotInfo.getAsr().getAccounts(), asrAccount);
                asr.setAccount(asrAccount);
                pushRobot.setAsr(asr);
                AiConfigura tts = new AiConfigura();
                BeanUtils.copyProperties(robotInfo.getTts(), tts);
                AiAccountBase ttsAccount = new AiAccountBase();
                BeanUtils.copyProperties(robotInfo.getTts().getAccounts(), ttsAccount);
                tts.setAccount(ttsAccount);
                pushRobot.setTts(tts);
                Category category = new Category();
                BeanUtils.copyProperties(robotInfo.getGateway(), category);
                pushRobot.setGateway(category);
                pushRobots.add(pushRobot);
            }
            pushTask.setRobots(pushRobots);
            if (Objects.nonNull(dialTask.getCompany())) {
                CompanyInfo companyInfo = new CompanyInfo();
                BeanUtils.copyProperties(dialTask.getCompany(), companyInfo);
                pushTask.setCompanyInfo(companyInfo);
            }

            log.info("推送的任务信息是：" + pushTask);
            Map<String, Object> map = new HashMap<>();
            map.put("cmd", "excute");
            map.put("task", pushTask);
            Object taskMap = JSONObject.toJSON(map);
            System.out.println(taskMap.toString());
            rabbitTemplate.convertAndSend("task", taskMap.toString());
            log.info("任务信息推送结束");
        } else {
            log.info("id：" + taskId + "的任务信息不存在");
        }
    }


}
